package datastructure.set;

import datastructure.map.HashMap;
import datastructure.map.Map;

import java.util.Iterator;

/**
 * Description：
 * Author: zhangc
 * Date：2017/7/22 23:32
 */
public class HashSet<T> implements Set<T>, Iterable<T> {

    private Map<T, Object> map = new HashMap<>();
    private static final Object object = new Object();

    @Override
    public boolean add(T value) {
        return map.put(value, object);
    }

    @Override
    public boolean contains(T value) {
        return map.containsKey(value);
    }

    @Override
    public void remove(T value) {
        map.remove(value);
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public Iterator<T> iterator() {
        return new SetItr<>(map.iterator());
    }

    public class SetItr<T> implements Iterator<T> {
        Iterator<Map.Entry<T, Object>> iterator;

        public SetItr(Iterator<Map.Entry<T, Object>> iterator) {
            this.iterator = iterator;
        }

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Override
        public T next() {
            return iterator.next().getKey();
        }
    }
}
